<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="pname">
        <el-input v-model="queryParams.pname" placeholder="请输入商品名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="车型" prop="chexing">
        <el-input v-model="queryParams.chexing" placeholder="请输入车型" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="零件号" prop="pid">
        <el-input v-model="queryParams.pid" placeholder="请输入零件号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="备注" prop="beizhu">
        <el-input v-model="queryParams.beizhu" placeholder="请输入备注" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery" v-if="!props.isSelect">重置</el-button>
        <el-button type="primary" @click="selectMultiple" v-if="props.isSelect">选择</el-button>

        <el-button type="danger" @click="add_select" v-if="props.isSelect">新增</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!props.isSelect">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['carrepair:peijian:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['carrepair:peijian:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['carrepair:peijian:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['carrepair:peijian:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="pjTable" v-loading="loading" :data="peijianList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="零件号" align="center" prop="pid" />
      <el-table-column label="商品名称" align="center" prop="pname" />
      <el-table-column label="车型" align="center" prop="chexing" />
      <el-table-column label="销售价" align="center" prop="xiaoshoujia" />
      <el-table-column label="备注" align="center" prop="beizhu" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['carrepair:peijian:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['carrepair:peijian:remove']">删除</el-button>

          <el-button type="danger" link @click="selectRow(scope.row)">选择</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改配件管理对话框 -->
    <el-dialog :title="title" v-model="open" width="80%" append-to-body>
      <el-form ref="peijianRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名称" prop="pname">
          <el-input v-model="form.pname" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="车型" prop="chexing">
          <el-input v-model="form.chexing" placeholder="请输入车型" />
        </el-form-item>
        <el-form-item label="销售价" prop="xiaoshoujia">
          <el-input v-model="form.xiaoshoujia" placeholder="请输入销售价" />
        </el-form-item>
        <el-form-item label="零件号" prop="pid">
          <el-input v-model="form.pid" placeholder="请输入零件号" />
        </el-form-item>
        <el-form-item label="备注" prop="beizhu">
          <el-input v-model="form.beizhu" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="图片上传" prop="img">
          <el-upload class="avatar-uploader" :action="uploadFileUrl" :show-file-list="false" :headers="headers"
            :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
            <img v-if="form.img" :src="serverUrl + form.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon">上传图片</i>
          </el-upload>
        </el-form-item>
        <el-form-item label="详情图片上传" prop="img">
          <div v-for="(item, index) in imgDetailsList" :key="index" style="float: left">
            <img :src="serverUrl + item" style="width:100px;height: 100px;" />
          </div>
          <div style="float: left">
            <el-upload class="avatar-uploader" :action="uploadFileUrl" :show-file-list="false" :headers="headers"
              :on-success="handleAvatarSuccess2" :before-upload="beforeAvatarUpload">
              <i class="el-icon-plus avatar-uploader-icon">上传图片</i>
            </el-upload>
          </div>
          <div class="clear"></div>
        </el-form-item>
        <el-form-item label="产品说明">
          <editor v-model="form.detialstxt" :min-height="192" />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Peijian">
import { getToken } from "@/utils/auth";
import {
  listPeijian,
  getPeijian,
  delPeijian,
  addPeijian,
  updatePeijian,
} from "@/api/carrepair/peijian";
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";

let pjTable = ref(null);
const { proxy } = getCurrentInstance();

const peijianList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    pname: null,
    chexing: null,
    pid: null,
    beizhu: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

let props = defineProps({
  isSelect: {
    type: Boolean,
    default: false,
  },
});

let emit = defineEmits(["checkRow", "multipleCheck", "closeWin"]);
const selectRow = (obj) => {
  emit("checkRow", obj);
};

const clearSelectRow = () => {
  handleQuery();
};

const add_select = () => {
  emit("closeWin", "/wxdnr/peijian/");
};

const selectMultiple = () => {
  let rows = pjTable.value.getSelectionRows();
  if (rows.length == 0) {
    ElMessage.error("请勾选要添加的数据！");
    return;
  }
  console.log("pjRows", rows);
  emit("multipleCheck", rows);
};

defineExpose({ clearSelectRow });

//定义图片详情列表
let imgDetailsList = reactive([]);
//图片上传
let serverUrl = ref(import.meta.env.VITE_APP_BASE_API);
let uploadFileUrl = serverUrl.value + "/common/upload"; // 上传文件服务器地址
let headers = {
  Authorization: "Bearer " + getToken(),
};
const handleAvatarSuccess = (res, file) => {
  form.value.img = res.fileName;
  //console.log('json',JSON.stringify(form));
};

const beforeAvatarUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 200;
  if (!isLt2M) {
    ElMessage.error("上传图片大小不能超过 200MB!");
  }
  return isLt2M;
};

const handleAvatarSuccess2 = (res, file) => {
  if (form.value.detialsimg == null || form.value.detialsimg.length == 0) {
    form.value.detialsimg = res.fileName;
  } else {
    form.value.detialsimg = form.value.detialsimg + "," + res.fileName;
  }
  imgDetailsList.push(res.fileName);
  //console.log('json',JSON.stringify(form));
};

/** 查询配件管理列表 */
function getList() {
  loading.value = true;
  listPeijian(queryParams.value).then((response) => {
    peijianList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    pname: null,
    chexing: null,
    xiaoshoujia: null,
    pid: null,
    CreateID: null,
    Creator: null,
    CreateDate: null,
    ModifyID: null,
    Modifier: null,
    ModifyDate: null,
    IsDeleted: null,
    beizhu: null,
    RowVersion: null,
    toApplet: null,
  };
  proxy.resetForm("peijianRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加配件管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getPeijian(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改配件管理";

    imgDetailsList.splice(0);
    if (form.value.detialsimg != null) {
      let imgsList = form.value.detialsimg.split(',');
      for (var i = 0; i < imgsList.length; i++) {
        imgDetailsList.push(imgsList[i]);
      }
    }

  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["peijianRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updatePeijian(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addPeijian(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除配件管理编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delPeijian(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "carrepair/peijian/export",
    {
      ...queryParams.value,
    },
    `peijian_${new Date().getTime()}.xlsx`
  );
}

getList();
</script>


<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.clear {
  clear: both;
}
</style>
